package com.cncqs.common;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.cncqs.base.MyResponseBody;
import com.cncqs.entity.LoginValidate;
import com.cncqs.service.ILoginValidateService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: cxy
 * @date: 2019/4/16 0016 上午 11:11
 */
@Aspect
@Component
public class MyAspect {
    private Logger logger = LoggerFactory.getLogger(MyAspect.class);

    @Autowired
    private ILoginValidateService loginValidateService;

    @Pointcut(value = "@annotation(com.cncqs.common.MyValidate)")
    public void annotationPointCut() {
    }

    @Around("annotationPointCut()")
    public Object doAround(ProceedingJoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String methodName = signature.getMethod().getName();
        logger.info("方法名：" + methodName);

        if(!validate()){
            MyResponseBody responseBody = MyResponseBody.failure(-2, "未登录");
            return responseBody;
        }
        try {
            return joinPoint.proceed();
        } catch (Throwable throwable) {
            return null;
        }
    }

    private boolean validate(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 实现自己的鉴权功能
        Wrapper wrapper = new EntityWrapper<LoginValidate>();
        wrapper.eq("token", request.getAttribute("token"));
        LoginValidate loginValidate = loginValidateService.selectOne(wrapper);
        if (loginValidate != null) {
            return true;
        }
        return false;
    }


}